<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-25
 * Time: 11:16
 */
namespace common\services;

use common\models\Tally;
use common\models\TallyPm;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * Class TallyPmService
 *
 * @package common\services
 * @desc 账本管理员相关
 */
class TallyPmService extends BaseService
{

    /**
     * @param $uid
     *
     * @return array
     * @desc 返回用户名下的账本 包括
     */
    public static function getTallyByUid($uid)
    {
        $where = [
            'uid'   => $uid,
            'state' => TallyPm::STATE_VALID // 只检索状态正常的账本
        ];
        $list = TallyPm::find()
            ->select('uid,tally_id,role,is_default,created_time')
            ->where($where)
            ->orderBy('is_default DESC,created_time ASC')
            ->limit(100)
            ->all();
        $retData = [] ;
        foreach ($list as $lv) {
            $tally = ArrayHelper::toArray($lv->tally);

            $tally['industry'] = explode(',',$tally['industry']); //所属行业转换为数组
            $retData[] = ArrayHelper::merge($tally,[
                'is_default'=>$lv->is_default,
                'day'=>(($tally['express_time'] - strtotime(date('Y-m-d')))/86400),
                'role'=>$lv->role,
                'role_name'=>TallyPm::getRoleName($lv->role)]);
        }
        return $retData ;
    }

    /**
     * @param $tallyId integer 账本ID
     * @return array
     * @throws
     * @desc 根据用户uid获取所有数据并缓存
     */
    public static function getUidsByTallyId($tallyId)
    {
        // 查表获取
        $where = [
            'tally_id'   => $tallyId,
        ];
        $list = TallyPm::find()
            ->select('uid,created_time')
            ->where($where)
            ->orderBy('created_time ASC')
            ->limit(100)
            ->asArray()
            ->all();
        return ArrayHelper::getColumn($list,'uid') ;
    }

    /**
     * @param $tallyId
     *
     * @return array
     * @desc 获取某账本下用户列表
     */
    public static function getUserListByTallyId($tallyId)
    {
        // 查表获取
        $where = [
            'tally_id'   => $tallyId,
        ];
        $list = TallyPm::find()
            ->where($where)
            ->orderBy('created_time ASC')
            ->limit(100)
            ->all();
        $retData = [] ;
        foreach ($list as $lv) {
            $user   = ArrayHelper::toArray($lv->user);
            $userPart = [
                'id'  => $user['id'],
                'uid'  => $user['id'],
                'username' => $user['username'],
                'mobile'   => $user['mobile'],
                'avatar'   => $user['avatar'],
                'projects_ids'   => $lv->projects_ids,
                'account_ids'   => $lv->account_ids,
            ] ;
            $retData[] = ArrayHelper::merge($userPart,[
                'created_time'=>$lv->created_time,
                'role'=>$lv->role,
                'role_name'=>TallyPm::getRoleName($lv->role)
            ]);
        }
        return $retData ;
    }

    /**
     * @param $uid
     * @param $tallyId
     *
     * @return array|\yii\db\ActiveRecord|null
     * @desc 获取用户与账本的绑定关系
     */
    public static function getOne($uid,$tallyId)
    {
        return TallyPm::find()
            ->where(['uid'=>$uid,'tally_id'=>$tallyId])
            ->limit(1)
            ->asArray()
            ->one();
    }

    /**
     * @param $uid
     * @throws
     * @return array
     * @desc 获取uid下所有的账本ID集合数组
     */
    public static function getTallyIdsByUid($uid)
    {
        // 查表获取
        $where = [
            'uid'   => $uid,
        ];
        // 从DB获取
        $list = TallyPm::find()
            ->select('tally_id')
            ->where($where)
            ->limit(100)
            ->asArray()
            ->all();
        return ArrayHelper::getColumn($list,'tally_id') ;
    }

    /**
     * @param $formData
     * @return bool
     */
    public static function create($formData)
    {
        $model = new TallyPm();
        $model->load($formData,'');
        if ($model->validate() && $model->save()) {
            // 如果增加的是出纳角色 调整账套类别为会计+出纳的审核模式 financial_type =2
            if($model->role == TallyPm::ROLE_CASHIER) {
                $tallyId = $formData['tally_id'];
                $tallyInfo = Tally::find()->where([
                    'id' => $tallyId
                ])->one();
                $tallyInfo->financial_type = Tally::FINANCIAL_TYPE_AUDIT;
                $tallyInfo->save();
            }
            return true ;
        }else{
            Yii::error('TallyPm insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($formData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * @param $tallyId integer 账本ID
     * @param $uid integer UID
     * @return bool
     * @desc 移除关系，无法移除管理员关系
     * @throws
     */
    public static function delete($tallyId,$uid)
    {
        $model = TallyPm::find()->where([
            'tally_id' => $tallyId,
            'uid'      => $uid,
        ])->one();
        if(!$model){
            self::setError('符合条件的数据不存在');
            return false ;
        }
        if($model->role == TallyPm::ROLE_ADMIN ) {
            self::setError('无法移除管理员身份');
            return false ;
        }
        if ($model->delete()) {
            // 寻找当前账套是否还存在出纳 如果没有出纳人员调整为 简单模式
            $count = TallyPm::find()->where([
                'tally_id' => $tallyId,
                'role' => TallyPm::ROLE_CASHIER
            ])->count();
            if(!$count) {
                $tallyInfo = Tally::find()->where([
                    'id' => $tallyId
                ])->one();
                $tallyInfo->financial_type = Tally::FINANCIAL_TYPE_SIMPLE;
                $tallyInfo->save();
            }
            return true ;
        }else{
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * 账本软删除
     * @param $tallyId
     */
    public static function delSoft($tallyId)
    {
        TallyPm::updateAll(['state' => TallyPm::STATE_INVALID],['tally_id' => $tallyId]);
    }

    /**
     * 设置某账本为用户的默认账本
     * @param $tallyId
     * @param $uid
     */
    public static function setDefault($tallyId,$uid)
    {
        // 先设置为0
        TallyPm::updateAll(['is_default' => 0],['uid'=>$uid,'is_default'=>1]);
        // 操作当前账本
        TallyPm::updateAll(['is_default' => 1],['tally_id' => $tallyId,'uid'=>$uid]);
    }

    /**
     * @param $uid
     * @param $tallyId
     *
     * @return mixed
     * @desc 获取用户与账本的角色关系
     */
    public static function getRole($uid,$tallyId)
    {
        $info = self::getOne($uid,$tallyId);

        return ArrayHelper::getValue($info,'role','false');
    }


    public static function getRoleUid($uid,$tallyId){
        $info = self::getOne($uid,$tallyId);
        $role =  ArrayHelper::getValue($info,'role','false');
        if($role =='pmanger'){
            return $uid;
        }
        return  null;
    }



    public static function get_projects($uid,$tallyId)
    {
        $info = self::getOne($uid,$tallyId);
        $projects = ArrayHelper::getValue($info,'projects_ids','');
        return explode(',',$projects);
    }

    public static function get_accounts($uid,$tallyId)
    {
        $info = self::getOne($uid,$tallyId);
        $account_ids = ArrayHelper::getValue($info,'account_ids','');
        return explode(',',$account_ids);
    }

    /**
     * 检查某个用户对账本的权限 后期扩展为权限节点可配置
     * @param        $uid
     * @param        $tallyId
     * @param string $permission | read write audit 等权限
     * @return boolean
     */
    public static function checkPermission($uid,$tallyId,$permission='read')
    {
        $role = self::getRole($uid,$tallyId);
        if($role == TallyPm::ROLE_ADMIN || $role == TallyPm::ROLE_MANAGER) {
            // 管理员 具有全局权限
            return true;
        }else if($role ==TallyPm::ROLE_ACCOUNTANT) {
            // 会计 不具备审核权限
            return $permission == 'audit' ? false : true ;
        }else if($role ==TallyPm::ROLE_CASHIER){
            // 出纳 不具备添加权限
            if($permission == 'write' ) return false; //
            return true;
        }else if($role ==TallyPm::ROLE_VIEWER){
            // 观察者 只具备read权限
            if($permission != 'read' ) return false;
            return true;
        }else if($role ==TallyPm::ROLE_PROJECT_MANAGER){

            if($permission == 'audit' ) return false;
            return true;
        }
        return false;
    }
    /**
     * 给用户设置项目权限
     * @param array $array
     * @return boolean
     */
    public static function setProjects(array $array)
    {
        $tally_pm = TallyPm::find()->where([
            'tally_id'=>$array['tally_id'],
            'uid'=>$array['uid']
        ])->one();

        $tally_pm->projects_ids = $array['projects_id'];
        $result = $tally_pm->save();
        if($result === false){
            return $result;
        }
        return true;
    }

    public static function setAccounts(array $array)
    {
        $tally_pm = TallyPm::find()->where([
            'tally_id'=>$array['tally_id'],
            'uid'=>$array['uid']
        ])->one();

        $tally_pm->account_ids = $array['account_ids'];
        $result = $tally_pm->save();
        if($result === false){
            return $result;
        }
        return true;
    }
}
